<template>
  <div :key="domKey">
    <el-button @click="selectCoordinate" type="primary">位置选择</el-button>
    <el-dialog
      title="位置选择"
      @close="cancelMap"
      v-model="codeVisible"
      width="900px"
    >
      <div class="flex flex-col justify-between">
        <vqqmap v-model="location" @update="mapChange" :options="options" />
        <div
          class="dialog-footer"
          style="padding-top: 50px; display: flex; justify-content: right"
        >
          <div>
            <el-button @click="cancelMap">取 消</el-button>
            <el-button type="primary" @click="handelOk">确 定</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
 
<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import vqqmap from "vue-qqmap";
const domKey = ref(0);
const formData = reactive<any>({});
const emit = defineEmits(["getLocation"]);
// 地图
const location = reactive({
  lat: "",
  lng: "",
  address: "",
});
const props = defineProps({
  atLocation: {
    type: String,
    default: "31.1269,104.3978",
  },
  address: {
    type: String,
    default: "德阳市人民政府",
  },
});
 
watch(
  [() => props.atLocation, () => props.address],
  ([newVal1, newVal2], [oldVal1, oldVal2]) => {
    if (newVal1) {
      location.lat = newVal1.split(",")[0];
      location.lng = newVal1.split(",")[1];
      location.address = newVal2;
    } else {
      location.latitude = "";
      location.longitude = "";
      location.address = "";
      return "";
    }
  },
  { immediate: true, deep: true }
);
const options = reactive({ key: "YP3BZ-UT6K3-CEQ3T-OUKDH-JFKIH-I5BR6" }); 
 
const codeVisible = ref(false);
// 弹出地图弹框
const selectCoordinate = () => {
  codeVisible.value = true;
  formData.latitude = location.lat;
  formData.longitude = location.lng;
  formData.address = location.address;
};
// 地图更换
const mapChange = (data) => {
  formData.latitude = data.lat;
  formData.longitude = data.lng;
  formData.address = data.address;
};
const cancelMap = () => {
  codeVisible.value = false;
  emit("getLocation", formData);
  domKey.value = domKey.value + 1;
};
const handelOk = () => {
  codeVisible.value = false;
  emit("getLocation", formData);
  domKey.value = domKey.value + 1;
};
</script>